leetcodeJS

Personal solution for leetcode problem using Javascript

View on GitHub

Problem

You are given an m x n matrix grid consisting of positive integers.

Perform the following operation until grid becomes empty:

Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them. Add the maximum of deleted elements to the answer.

Note that the number of columns decreases by one after each operation.

Return the answer after performing the operations described above.

Example 1:

Input: grid = [[1,2,4],[3,3,1]] Output: 8 Explanation: The diagram above shows the removed values in each step.

Example 2:

Input: grid = [[10]] Output: 10 Explanation: The diagram above shows the removed values in each step.

Constraints:

m == grid.length n == grid[i].length 1 <= m, n <= 50 1 <= grid[i][j] <= 100

Pre analysis

The approach is to sort the array and pick the maximum value across all columns for a particular index. The result would be sum of all maximum values.

Another solution

/**
 * @param {number[][]} grid
 * @return {number}
 */
var deleteGreatestValue = function (grid) {
  ans = 0;
  while (grid[0].length > 0) {
    del = 0;
    for (let i = 0; i < grid.length; i++) {
      max = Math.max(...grid[i]);
      grid[i].splice(grid[i].indexOf(max), 1);
      if (max > del) {
        del = max;
      }
    }
    ans = ans + del;
  }
  return ans;
};